#!/usr/bin/perl



$ifconfig_out = readpipe("ifconfig eth1");

#print $ifconfig_out;

@fields = split(" ", $ifconfig_out ); 

#print @fields;

$my_mac = $fields[4];

 
 
#print "mac=$my_mac\n";


open(mac_mapping_file, "<mac.addr"); 
while(<mac_mapping_file>) 
{ 
    my($line) = $_; 
    chomp($line); 
    
    if ( $line =~ /^\s*$/ || $line =~ /\#/ ) 
    { 
	next; 
    }

    @entries = split(' ', $line); 
    my($ip) = $entries[0]; 
    my($mac) = $entries[1]; 
    $ip_mac_map{ $ip } = $mac;
    if ($mac eq $my_mac) { 
	$my_ip = $ip; 
	break; 
    }
}

close(mac_mapping_file);


print "-----------IP MAC address mapping------------\n";
for my $ip (keys( %ip_mac_map ) ) { 
   print "$ip = $ip_mac_map{$ip}\n"; 
}
print "--------------------------------------------\n\n";

if ($my_ip) { 
    print "Local MAC = $my_mac\n"; 
    print "Local IP  = $my_ip\n"; 
    open(localhost_file, ">/etc/localhost"); 
	print localhost_file "$my_ip\n" ;    
	close(localhost_file); 
} else { 
    print "Cannot find ip address matching the local mac address $my_mac, check your mac.addr file\n"; 
    exit(1); 
}


#@TODO: call the network_setup script


open(topology_file, "< topology.conf"); 
while(<topology_file>) 
{ 
    my($line) = $_; 
    chomp($line); 
    
    if ( $line =~ /^\s*$/ || $line =~ /\#/ ) 
    { 
	next; 
    }
    
    @entries = split(' ', $line); 
    my($ip1) = $entries[0]; 
    my($ip2) = $entries[1]; 

    push ( @{ $neighbor{$ip1} }, $ip2 ); 
    push ( @{ $neighbor{$ip2} }, $ip1 ); 

}

print "\n-----------network neighbor setup-----------\n";
for my $ip (keys( %neighbor ) ) {    
   print "$ip = @{$neighbor{$ip}} \n"; 
}
print "--------------------------------------------\n\n";

# find all the mac address that are not my neighbors and put them into the filter list

@my_neighbors = @{${neighbor{$my_ip}}}; 

print "local neighbors = @my_neighbors\n";

@all_nodes = keys(%ip_mac_map); 

#find all the nodes not my neighbors and my self. 

push @my_neighbors, $my_ip; 

my %seen; # lookup table
my @aonly;# answer

# build lookup table
@seen{@my_neighbors} = ();

foreach $node (@all_nodes) {
    push(@aonly, $node) unless exists $seen{$node};
}

my @non_neighbors = @aonly; 


print "setting local ip address to $my_ip\n"; 

system("./network_setup", $my_ip); 

# now filter out all the non neighbor nodes
@args = ( "iptables", "-t", "raw", "-F"); 
system(@args) == 0 ||  die "system @args failed: $?";
print "setting filtering rules for non-neighbor nodes: @non_neighbors\n";
foreach $node (@non_neighbors) { 
    my($mac) = $ip_mac_map{$node}; 
    system("./mac_filter", $mac); 
}





